package com.aaa.sso.service;

import com.aaa.entity.Menu;
import com.aaa.entity.User;
import com.aaa.sso.fegin.MenuFeign;
import com.aaa.sso.fegin.UserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: his-open-parent
 * @description:
 * @author: 闫克起2
 * @create: 2023-03-20 10:10
 **/
@Service
public class MyUserService implements UserDetailsService {
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private MenuFeign menuFeign;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //手机号
        User user = userFeign.getByUsername(username);
        if(user==null){
            throw new RuntimeException("账号不存在");
        }
        //查询该用户具有的权限。
        List<Menu> menuList = menuFeign.findByUserid(user.getUserId());
        Collection<SimpleGrantedAuthority> authorities=menuList.stream().map(item->new SimpleGrantedAuthority(item.getPercode())).collect(Collectors.toList());
        return  new org.springframework.security.core.userdetails.User(user.getPhone(),user.getPassword(),authorities);
    }




}
